package com.zcyr.controller;

import com.zcyr.core.AbstractDatabaseEnvironment;
import com.zcyr.core.AbstractDatabaseEnvironmentManager;
import com.zcyr.exception.DatabaseEnvironmentManagerException;
import com.zcyr.pojo.PgUser;
import com.zcyr.util.DatabaseTool;
import com.zcyr.util.JsonBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

@RestController()
@RequestMapping("test")
public class TestController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    AbstractDatabaseEnvironmentManager databaseEnvironmentManager;

    @Autowired
    DatabaseTool databaseTool;

    @Autowired
    DataSource dataSource;

    @RequestMapping("/")
    public JsonBody testApi(){
        return JsonBody.ok("接口请求成功!");
    }

    @RequestMapping("/create/env")
    public JsonBody testCreateEnv() throws DatabaseEnvironmentManagerException {
        AbstractDatabaseEnvironment databaseEnvironment = databaseEnvironmentManager.getAvailableEnvironment();

        return JsonBody.ok(String.format("数据库环境创建成功, 用户名: %s", databaseEnvironment.getUsername()));
    }

    @RequestMapping("/drop/trymeUser")
    public JsonBody testDropTrymeUser() throws SQLException {
        ArrayList<PgUser> users = databaseTool.getUsers("usename like 'tryme_user_%'");
        int count = 0;
        try(Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()){
            for (PgUser user : users){
                stmt.executeUpdate("drop user " + user.getUsename() + " CASCADE");
                count += 1;
            }
            return JsonBody.ok(String.valueOf(count));
        }
    }

    /**
     * 测试从环境管理取出，或新建数据库环境, 并使用该环境执行一条建表指令后释放该环境.
     */
    @RequestMapping("/1")
    public JsonBody test1() throws DatabaseEnvironmentManagerException {
        AbstractDatabaseEnvironment environment = null;
        try{
            environment = databaseEnvironmentManager.getAvailableEnvironment();
            environment.executeSQL("create table test112(\n" +
                    "\tusername VARCHAR(32)\n" +
                    ")");
            databaseEnvironmentManager.releaseDatabaseEnvironment(environment.getUuid());
            return JsonBody.ok("test-1 success!! uuid: " + environment.getUuid()).put("status", databaseEnvironmentManager.status());
        } catch (Exception e){
            if (environment != null){
                databaseEnvironmentManager.reportErrorEnvironment(environment);
            }
            e.printStackTrace();
            return JsonBody.error(e.getMessage());
        }
    }

    @RequestMapping("/2")
    public JsonBody test2() {
        try{
            AbstractDatabaseEnvironment environment = databaseEnvironmentManager.getAvailableEnvironment();
            environment.executeSQL("create table test112(\n" +
                    "\tusername VARCHAR(32)\n" +
                    ")");
            databaseEnvironmentManager.releaseDatabaseEnvironment(environment.getUuid());
            return JsonBody.ok("test-2 success!! uuid: " + environment.getUuid());
        } catch (Exception e){
            e.printStackTrace();
            return JsonBody.error(e.getMessage());
        }
    }
}